/* eslint-disable react-hooks/exhaustive-deps */
import React, { useContext, useEffect } from 'react'
import { Row, Descriptions, Statistic, Empty } from 'antd';
import styles from './index.less'
import ReactEcharts from "echarts-for-react";
import { ArrowDownOutlined, ArrowUpOutlined } from '@ant-design/icons';
import { useState } from 'react';
import { CourseContext } from '..';
import { echartOption } from '@/utils/echartsUtils';
import moment from 'moment';
import { getgokuCode, userGameStatDetail } from '@/services/goku';
import { Link } from 'react-router-dom';
export default function WkPlay() {
  const ctx = useContext(CourseContext);

  const [gradeInfo, setGrade] = useState<any>({})
  const [nearPower, setNearPower] = useState<any[]>()
  const { addedPower, curPower, allCount, allWinCount
    , monthTotalCount, monthWinCount, weekTotalCount, weekWinCount } = gradeInfo || {}

  useEffect(() => {
    (async () => {
      const res = await getgokuCode({ uid: ctx.uid, activityId: ctx.courseId })
      setGrade(res.result);
    })();
    (async () => {
      const res = await userGameStatDetail({ uid: ctx.uid, pageSize: 8 })
      setNearPower(res?.result?.records);
    })()


  }, [ctx])
  const xData = nearPower?.map((item) => {
    return moment(item.createTime).format('MM/DD')
  })

  const data: any = nearPower?.map((item) => {
    return { value: item?.afterPower, type: item?.isWin }
  })
  for (let i = 0; i < data?.length; i++) {
    data[i] = {
      value: data[i].value,
      itemStyle: {
        color: data[i].type == 1 ? 'green' : 'red'
      }
    }
  }

  const option = {
    title: {
      text: '近期战绩'
    },
    tooltip: {
      trigger: 'axis',
      formatter: '{b} : {c}'
    },

    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },

    xAxis: {
      type: 'category',
      axisTick: {
        show: false
      },
      data: xData,
      axisLabel: {
        formatter: function (value: any) {
          return moment(value).format('MM/DD')
        }
      }
    },
    yAxis: {
      type: 'value',
      min: function (value: any) {//取最小值向下取整为最小刻度
        return Math.floor(value.min)
      },
      max: function (value: any) {//取最大值向上取整为最大刻度
        return Math.ceil(value.max)
      },
      minInterval: 1,
    },

    series: [
      {
        type: 'line',
        stack: 'Total',
        data: data,
        symbol: 'circle',
        symbolSize: 18,
        itemStyle: {
          normal: {
            color: '',
            lineStyle: {
              color: 'black'
            }
          }
        },
      }
    ]
  };

  const dataList = [
    { value: allWinCount, name: `胜利` },
    { value: allCount - allWinCount, name: `失败` },
  ]
  const dataList1 = [
    { value: monthWinCount, name: `胜利` },
    { value: monthTotalCount - monthWinCount, name: `失败` },
  ]
  const dataList2 = [
    { value: weekWinCount, name: `胜利` },
    { value: weekTotalCount - weekWinCount, name: `失败` },
  ]

  return (
    <div className={styles.play_container} >
      <Row justify="end">
        <Link key="one" to={`/course/userGame/chess?id=${ctx?.uid}&courseId=${ctx?.courseId}`} target="_blank">
          <a>查看棋谱</a>
        </Link>
      </Row>
      <Descriptions style={{ marginBottom: "20px" }} layout="vertical" bordered>
        <Descriptions.Item labelStyle={{ fontWeight: 'bold' }} label="开课前悟空战力">{Number(curPower) - Number(addedPower) || 0}</Descriptions.Item>
        <Descriptions.Item labelStyle={{ fontWeight: 'bold' }} label="当前悟空战力">{curPower || 0}</Descriptions.Item>
        <Descriptions.Item labelStyle={{ fontWeight: 'bold' }} label="提升">
          <Row align="middle">
            {
              addedPower ?
                Number(addedPower) >= 0 ?
                  <Statistic
                    value={addedPower}
                    valueStyle={{ color: '#cf1322' }}
                    prefix={<ArrowUpOutlined />}
                  /> : <Statistic
                    value={addedPower}
                    valueStyle={{ color: '#3f8600' }}
                    prefix={<ArrowDownOutlined />}
                  /> : '-'
            }
          </Row>
        </Descriptions.Item>
      </Descriptions>
      {
        data && data.length !== 0 ?
          <ReactEcharts notMerge option={option} /> : <Empty description={'关卡还没有解锁哦'} image={Empty.PRESENTED_IMAGE_SIMPLE} />
      }

      <div>
        <Row style={{ marginTop: '20px' }}>
          <div style={{ flex: 1, marginBottom: '15px', position: 'relative' }}>
            <div className={styles.font}>累计对局（{gradeInfo?.allCount || 0}）</div>
            {
              allCount ? <>
                <ReactEcharts notMerge option={echartOption(dataList)} />
              </> : <Empty description={'还没有对弈记录哦'} style={{ position: "relative", top: "50%", transform: 'translateY(-50%)' }} image={Empty.PRESENTED_IMAGE_SIMPLE} />
            }
          </div>

          <div style={{ flex: 1, marginBottom: '15px', position: 'relative' }}>
            <div className={styles.font}>本月对局（{gradeInfo?.monthTotalCount || 0}）</div>
            {
              monthTotalCount ? <>
                <ReactEcharts notMerge option={echartOption(dataList1)} />
              </> : <Empty description={'还没有对弈记录哦'} style={{ position: "relative", top: "50%", transform: 'translateY(-50%)' }} image={Empty.PRESENTED_IMAGE_SIMPLE} />
            }
          </div>
          <div style={{ flex: 1, marginBottom: '15px', position: 'relative' }}>
            <div className={styles.font}>本周对局（{gradeInfo?.weekTotalCount || 0}）</div>
            {
              weekTotalCount ? <>
                <ReactEcharts notMerge option={echartOption(dataList2)} />
              </> : <Empty description={'还没有对弈记录哦'} style={{ position: "relative", top: "50%", transform: 'translateY(-50%)' }} image={Empty.PRESENTED_IMAGE_SIMPLE} />
            }
          </div>
        </Row>
      </div>
    </div >
  )
}
